package com.szdtoo.controller.exceptionHandler;

import com.szdtoo.exception.MyException;
import com.szdtoo.response.Result;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常控制处理类
 */
@ControllerAdvice
public class DefaultExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(IncorrectCredentialsException.class)
    @ResponseBody
    public Result processIncorrectCredentialsException(IncorrectCredentialsException e) {
        logger.error("账户名或者密码错误:{}",e.getMessage());
        return Result.failed("账户名或者密码错误");
    }

    @ExceptionHandler(LockedAccountException.class)
    @ResponseBody
    public  Result processLockedAccountException(LockedAccountException e) {
        logger.error("用户已经被冻结:{}",e.getMessage());
        return Result.failed("用户已经被冻结");
    }

    @ExceptionHandler(ExcessiveAttemptsException.class)
    @ResponseBody
    public  Result processExcessiveAttemptsException(ExcessiveAttemptsException e) {
        logger.error("密码输入错误次数超过5次:{}",e.getMessage());
        return Result.failed("密码错误超过5次，10分钟内不能登陆");
    }


    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public  Result processAuthenticationException(AuthenticationException e) {
        e.printStackTrace();
        logger.error("账户身份验证失败:{}",e.getMessage());
        return Result.failed("账户身份验证失败");
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public Result processUnauthorizedException(UnauthorizedException e) {
        e.printStackTrace();
        logger.error("授权异常:{}",e.getMessage());
        return Result.verify("没有该权限");
    }

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result processMyException(MyException e) {
        logger.error("自定义异常:{}",e.getMessage());
        return Result.failed(e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result processException(Exception e) {
        e.printStackTrace();
        logger.error("系统异常:{}",e.getMessage());
        return Result.failed("系统异常，请联系管理员");
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result processRuntimeException(RuntimeException e) {
        e.printStackTrace();
        logger.error("系统异常:{}",e.getMessage());
        return Result.failed("系统异常，请联系管理员");
    }

}
